import {
  KeywordModel
} from '../../models/keyword.js'
import {
  BookModel
} from '../../models/book.js'
import {
  paginationBev
} from '../behaviors/pagination.js'
const keywordModel = new KeywordModel()
const bookModel = new BookModel()

Component({
  behaviors: [paginationBev],
  properties: {
    more: {
      type: String,
      observer: 'loadMore'
    }
  },
  data: {
    historyWords: [],
    hotWords: [],
    searching: false,
    word: '',
    loading: false,
    loadingCenter: false
  },
  lifetimes: {
    attached() {
      this.setData({
        historyWords: keywordModel.getHistory()
      })
      keywordModel.getHot().then(res => {
        this.setData({
          hotWords: res.hot
        })
      })
    }
  },
  methods: {
    onCancel(e) {
      this.triggerEvent('cancel', {}, {})
      this.initialize()
    },

    onDelete(e) {
      this._closeResult()
      this.initialize()
    },

    onConfirm(e) {
      this._showResult()
      this._showLoadingCenter()
      const word = e.detail.value || e.detail.text
      bookModel.search(0, word)
        .then(res => {
          this.setMoreData(res.books)
          this.setTotal(res.total)
          this.setData({
            word
          })
          keywordModel.addToHistory(word)
          this._hideLoadingCenter()
        })
    },

    loadMore() {
      if (!this.data.word || this.isLocked()) {
        return
      }
      if (this.hasMore()) {
        this.locked()
        bookModel.search(this.getCurrentStart(), this.data.word)
          .then(res => {
            this.setMoreData(res.books)
            this.unLocked()
          }, () => {
            this.unLocked()
          })
      }
    },

    _showResult() {
      this.setData({
        searching: true
      })
    },

    _closeResult() {
      this.setData({
        searching: false,
        word: ''
      })
    },

    _showLoadingCenter() {
      this.setData({
        loadingCenter: true
      })
    },

    _hideLoadingCenter() {
      this.setData({
        loadingCenter: false
      })
    }
  },
  externalClasses: ['iconfont', 'iconsearch', 'iconroundclosefill']
})